package util.thread.threadpool;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 只创建唯一的工作线程来执行任务，保证线程按照指定的书序执行，保证顺序的执行任务。
 *
 * @author: Lidong
 * @time: 2020/8/6 21:30
 **/
public class SingleThreadExecutorTest {

    private static final Logger logger = LoggerFactory.getLogger(SingleThreadExecutorTest.class);
    private static final int MILLIS = 20000;
    private static final int TWO_THOUSAND = 2000;

    private void useSingleThreadExecutor() {
        // 单线程的线程池底层是创建一个核心线程为1最大线程为1的 threadPool
        ExecutorService executor = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 5; i++) {
            int index = i;
            executor.execute(() -> {
                try {
                    Thread.sleep(TWO_THOUSAND);
                } catch (InterruptedException e) {
                    logger.error(e.getMessage(), e);
                    Thread.currentThread().interrupt();
                }
                logger.info("{}   {}", Thread.currentThread().getName(), index);
            });
        }
        executor.shutdown();
    }

    @Test
    public void test() {
        useSingleThreadExecutor();
        try {
            Thread.sleep(MILLIS);
        } catch (InterruptedException e) {
            logger.error(e.getMessage(), e);
            Thread.currentThread().interrupt();
        }
    }

}
